const express = require('express')
const multiparty = require('multiparty')
const fs = require('fs')
const path = require('path')
const config = require('../config/config')
const thunkify = require('thunkify')
const router = express.Router()

/**上传需要的util方法 */
const {
  mkdirs, formatJson, thunkifyCB, runThunkGen, gmOper
} = require('./upload-util')


// 图片尺寸配置
const imageSize = config.imageSize;
// 默认上传路径
const uploadDir = config.path.temPath;


// 上传失败返回
const uploadErr = (res, err) => {
	console.log('err', err);
	res.writeHead(200, {'content-type': 'text/plain;charset=utf-8'});
  res.end("{'status':200, 'message': '上传失败！'}");
}
// 上传成功返回
const uploadOk = (res, rePath) => {
	console.log('ok', rePath);
	res.writeHead(200, {'content-type': 'text/plain;charset=utf-8'});

	const pathArr = rePath.split(path.sep);
	const tem = pathArr.splice(pathArr.length - 3, pathArr.length - 1);
	const rpath = '/' + tem.join('/');

  res.end(JSON.stringify(
		{
			status: 400,
			message: '上传成功！',
			data: {
				path: rpath
			}
		}
  ));
}


/**thunk封装 */
const mkdirsTh = thunkifyCB(mkdirs);
const gmOperTh = thunkifyCB(gmOper);
const fsunlinkTh = thunkify(fs.unlink);
const fsrenameTh = thunkify(fs.rename);


// 图片上传服务
router.post('/gopost', (req, res) => {
	// 文件夹需存在
	const form = new multiparty.Form({ uploadDir });
	form.parse(req, (err, fields, files) => {
		if(err) {
			uploadErr(res, err);
		} else {

			/**取得附带参数 */
			const f_fields = formatJson(fields);
			const {
				did, name, type
			} = f_fields;


			/**取得文件，目前数组只有一个元素 */
			const image = files[name][0];

			/**取得文件信息 */
			const originalFilename = image.originalFilename;// 原文件名
			const oldPath = path.join('./', image.path);// 原相对路径
			const oldDir = path.dirname(oldPath);// 原相对目录路径
			const randomDir = path.basename(oldPath, path.extname(image.originalFilename));// 文件随机码
			const reDir = path.join(config.path.minPath, did, type);// 自定义相对目录路径
			const thumbDir = path.join(config.path.thumbPath, did, type);// 自定义缩略图相对路径
			const imgSize = image.size / 1024 / 1024;// 文件大小，mb

			/**
			 * 开始进行自定义目录保存操作、缩略图操作
			 */
			runThunkGen(function* () {
				yield mkdirsTh(reDir);// 保证目录存在
				const	rePath = path.join(reDir, originalFilename);// 需要跟换的新路径
				if(type !== 'headImg') {
					yield gmOperTh(oldPath, rePath, imageSize.worksImg);
					yield mkdirsTh(thumbDir);// 缩略图目录
					const thumbPath = path.join(thumbDir, originalFilename);// 缩略图路径
					yield gmOperTh(oldPath, thumbPath, imageSize.thumbImg);
				} else {
					yield gmOperTh(oldPath, rePath, imageSize.headImg);
				}
				// 删除temp文件
				yield fsunlinkTh(oldPath);
				uploadOk(res, rePath);
			});
		}
	});
});

router.post('/gofile', (req, res) => {
	const form = new multiparty.Form({ uploadDir });
	form.parse(req, (err, fields, files) => {
		if(err) {
			uploadErr(res, err);
		} else {

			const f_fields = formatJson(fields);
			const {
				did, name
			} = f_fields;

			const file = files[name][0];

			const originalFilename = file.originalFilename;// 原文件名
			const oldPath = path.join('./', file.path);// 原相对路径
			const oldDir = path.dirname(oldPath);// 原相对目录路径
			const randomDir = path.basename(oldPath, path.extname(file.originalFilename));// 文件随机码
			const reDir = path.join(config.path.minPath, did, 'fujian');// 自定义相对目录路径
			const imgSize = file.size / 1024 / 1024;// 文件大小，mb


			runThunkGen(function* () {
				yield mkdirsTh(reDir);
				const rePath = path.join(reDir, originalFilename);// 更换路径
				yield fsrenameTh(oldPath, rePath);
				yield fsunlinkTh(oldPath);
				uploadOk(res, rePath);
			});

		}
	});
});

module.exports = router;